package chess

import (
	"errors"
	"log"
)

//在安全的情况下，使用此方法
func (p *Piece) shift(point Point) (err error) {
	if point.withinRange() {
		p.Row = point.Row
		p.Line = point.Line
		return nil
	}
	return errors.New("out of range")
}

//RowPiece 返回指定列点的棋子
func (p *Piece) RowPiece() (up []*Piece, down []*Piece) {
	//下面的
	for i := p.Line + 1; i <= MaxLine; i++ {
		if _, ok := p.chessboard.M[Point{i, p.Row}]; ok {
			down = append(down, p.chessboard.M[Point{i, p.Row}].(*Piece))
		}
	}
	for i := p.Line - 1; i >= MinLine; i-- {
		if _, ok := p.chessboard.M[Point{i, p.Row}]; ok {
			up = append(up, p.chessboard.M[Point{i, p.Row}].(*Piece))
		}
	}
	return
}

func (p *Piece) LinePiece() (left []*Piece, right []*Piece) {
	//
	for i := p.Row + 1; i <= MaxRow; i++ {
		if _, ok := p.chessboard.M[Point{p.Line, i}]; ok {
			right = append(right, p.chessboard.M[Point{p.Line, i}].(*Piece))
		}
	}
	for i := p.Row - 1; i >= MinRow; i-- {
		if _, ok := p.chessboard.M[Point{p.Line, i}]; ok {
			left = append(left, p.chessboard.M[Point{p.Line, i}].(*Piece))
		}
	}
	return
}

//delete 不安全，测试用
func (p *Piece) delete() {
	log.Println("delete", p.Name, p.Point)
	p.Status = false
	delete(p.chessboard.M, p.Point)
}

// unsafeMove 强制移动棋子，不安全，测试用
func (p *Piece) unsafeMove(point Point) {
	log.Println("强制移动")
	delete(p.chessboard.M, p.Point)
	p.chessboard.M[point] = p
	p.Point = point
}

func (p *Piece) MoveTo(point Point) (msg string, err error) {
	if p.Name == "RedCannon" || p.Name == "BlaCannon" {
		return p.piece.(*Cannon).MoveTo(point)
	} else if p.Name == "BlaChariot" || p.Name == "RedChariot" {
		return p.piece.(*Chariot).MoveTo(point)
	} else if p.Name == "BlaHorse" || p.Name == "RedHorse" {
		return p.piece.(*Horse).MoveTo(point)
	} else if p.Name == "BlaElephant" || p.Name == "RedElephant" {
		return p.piece.(*Elephant).MoveTo(point)
	} else if p.Name == "BlaGuards" || p.Name == "RedGuards" {
		return p.piece.(*Guard).MoveTo(point)
	} else if p.Name == "BlaKing" || p.Name == "RedKing" {
		return p.piece.(*King).MoveTo(point)
	} else if p.Name == "BlaSoldier" || p.Name == "RedSoldier" {
		return p.piece.(*Soldier).MoveTo(point)
	}
	return "", errors.New("waring")
}

//func (p *Piece) LinePiece() (left []Piece, right []Piece) {
//	left = make([]Piece, 2)
//	right = make([]Piece, 2)
//	for k, v := range p.chessboard.M {
//		if k.Line == p.Line && k.Row > p.Row {
//			right = append(right, *v)
//		}
//		if k.Line == p.Line && k.Row < p.Row {
//			left = append(left, *v)
//		}
//	}
//	return
//}
